<?php
namespace app\api\service\uniapp\goodscart;

use app\api\model\Region;
use app\api\model\ShopPayOrder;
use app\api\model\ShopPayOrderGoods;
use app\api\model\ShopYiwu;
use app\api\model\ShopYiwuCart;
use app\api\model\UserStore;
use app\common\controller\Api;
use think\Db;

class GoodsCart10 extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function get_goods($goodsid){
        if(empty($goodsid)){
            $this->error("参数错误");
        }
        $goods = ShopYiwu::where('id',$goodsid)->find();
        if(!$goods){
            $this->error("商品不存在");
        }
        $goods['goods_pic'] = get_image($goods['main_pics']);
        $goods['countdown'] = calculateTimeDifference($goods['end_time']);
        $shop = UserStore::where('id',$goods['shop_id'])->find();
        $shop['shop_img'] = config('site_url').str_replace('/public','',$shop['store_img'][0]);;
        $goods['shop'] = $shop;
        $this->success("加载成功",$goods);
    }

    /**
     * 加入购物车
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add_cart(){
        $user = session('authuser');
        //接收参数
        $goodsid = $this->request->param('goodsid');
        $store_id = $this->request->param('store_id');
        //查询商品
        $goods = ShopYiwu::where('id',$goodsid)->find();
        $cartdata = [
            'user_id'=>$user['user_id'],
            'goods_id'=>$goodsid,
            'goods_name'=>$goods['title'],
            'market_price'=>$goods['market_price'],
            'goods_price'=>$goods['shop_price'],
            'goods_num'=>1,
            'add_time'=>time(),
            'store_id'=>$store_id,
            'total_price'=>$goods['shop_price'],
            'goods_pic'=>get_thumb_image(unserialize( $goods['main_pics'])[0],0,300),
        ];
        $cok = ShopYiwuCart::create($cartdata,true);
        $cartService = new GoodsCart();
        $cart = $cartService->loadGoodsCart($user['user_id'],$store_id);
        $this->success("加入购物车成功",$cart);
    }

    /**
     * 修改购物车
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function update_cart(){
        $user = session('authuser');
        //接收参数
        $goodsid = $this->request->param('goodsid');
        $store_id = $this->request->param('store_id');
        $value = $this->request->param('value');
        //查询购物车
        $cart = ShopYiwuCart::where(['goods_id'=>$goodsid,'store_id'=>$store_id,'user_id'=>$user['user_id']])->find();
        if($value==0){
            ShopYiwuCart::where(['goods_id'=>$goodsid,'store_id'=>$store_id,'user_id'=>$user['user_id']])->delete();
        }else{
            $cart->goods_num = $value;
            $cart->total_price = bcmul($cart['goods_price'],$value,2);
            $cart->save();
        }

        $cartService = new GoodsCart();
        $cart = $cartService->loadGoodsCart($user['user_id'],$store_id);
        $this->success("加入购物车成功",$cart);
    }

    public function del_cart(){
        $user = session('authuser');
        //接收参数
        $store_id = $this->request->param('store_id');
        //删除购物车
        $deletecartok = ShopYiwuCart::where(['user_id'=>$user['user_id'],'store_id'=>$store_id])->delete();
        if($deletecartok){
            $this->success('清空购物车成功');
        }else{
            $this->error("清空购物车失败");
        }
    }

    /**
     * 购物车生成订单
     */
    public function createorder(){
        $user = session('authuser');
        //接收参数
        $store_id = $this->request->param('store_id');
        $address_id = $this->request->param('address_id',0);
        //获取购物车数据
        $cart = ShopYiwuCart::where(['user_id'=>$user['user_id'],'store_id'=>$store_id])->select();
        if(!$cart){
            $this->error('暂无购物车数据');
        }
        $money = ShopYiwuCart::where(['user_id'=>$user['user_id'],'store_id'=>$store_id])->sum('total_price');
        if(!$user){
            return tok(-1,'用户不存在');
        }

        $shop = UserStore::where(['id'=>$store_id,'is_check'=>1])->find();
        if(!$shop){
            return tok(-2,'店铺不存在或以下架');
        }
        foreach ($cart as $k=>$v){
            $goods = ShopYiwu::where('id',$v['goods_id'])->find();
            if($goods['is_check']!=1 || $goods['is_on_sale']!=1){
                return tok(-3,"商品".$goods['title']."已下架");
            }
            if($goods['xiangou']>0&&$v['goods_num']>$goods['xiangou']){
                return tok(-4,"商品".$goods['title']."超出每人限购数量");
            }
            if($goods['store_count']<$v['goods_num']){
                return tok(-5,"商品".$goods['title']."库存不足");
            }
        }


        Db::startTrans();
        $trans_ok=true;

        //生成总订单
        $torder['user_id']=$user['user_id'];
        $torder['order_sn']=get_order_sn();
        $torder['shop_user_id']=$shop['user_id'];
        $torder['order_money']=$money;
        $torder['address_id']=$address_id;
        $torder['remark']='商城总订单';
        $torder['status']=0;
        $torder['hexiao_code']=get_order_sn(3);
        $torder['order_type']=7;
        $torder['create_time']=time();
        $torderadd=ShopPayOrder::create($torder,true);
        if(!$torderadd){
            $trans_ok = false;
        }
        //生成订单商品
        $orderGoodsList = array();
        foreach ($cart as $k=>$v){
            $goods = ShopYiwu::where('id',$v['goods_id'])->find();
            $orderGoodsItem['order_id'] = $torderadd->id;
            $orderGoodsItem['goods_id'] = $v['goods_id'];
            $orderGoodsItem['goods_name'] = $v['goods_name'];
            $orderGoodsItem['goods_pic'] = $v['goods_pic'];
            $orderGoodsItem['goods_num'] = $v['goods_num'];
            $orderGoodsItem['goods_price'] = $v['goods_price'];
            $orderGoodsItem['total_price'] = $v['total_price'];
            $orderGoodsItem['ratio'] = $goods['ratio'];
            $orderGoodsItem['bargain_price'] = $goods['bargain_price'];
            $orderGoodsItem['createtime'] = time();
            array_push($orderGoodsList,$orderGoodsItem);
        }
        $spog = new ShopPayOrderGoods();
        $orderGoodsOk = $spog->allowField(true)->saveAll($orderGoodsList);
        if(!$orderGoodsOk){
            $trans_ok = false;
        }
        //删除购物车
        $deletecartok = ShopYiwuCart::where(['user_id'=>$user['user_id'],'store_id'=>$store_id])->delete();
        if(!$deletecartok){
            $trans_ok = false;
        }
        //转账先以消费券为主，消费券不足则调用微信支付
        if($user['ywq']>=$money){ //消费券够付
            //生成店铺订单
            $data['user_id']=$user['user_id'];
            $data['order_sn']=get_order_sn();
            $data['shop_user_id']=$shop['user_id'];
            $data['money']=$money;
            $data['order_money']=$money;
            $data['money_type']=6;
            $data['remark']='商城订单';
            $data['status']=1;
            $data['order_type']=4;
            $data['create_time']=time();
            $data['pay_time']=time();
            $data['address_id']=$address_id;
            $data['total_order_id']=$torderadd->id;
            $shopadd=ShopPayOrder::create($data,true);

            if($shopadd){
                //进行支付
                $ok1 = new_finance_record_and_add_money($user['user_id'],$money,6,2,203,$shopadd->id,$data['order_sn']);
                if(!$ok1){
                    $trans_ok=false;
                }
            }else{
                $trans_ok=false;
            }
            if($trans_ok){
                //标志总订单为已支付
                $torderok = ShopPayOrder::where("id",$torderadd->id)->update([
                    'status'=>1,
                    'money_type'=>6,
                    'pay_time'=>time(),
                    'finish_time'=>time(),
                ]);
                Db::commit();

                $result['code']=2;
                $result['money']=$money;
                $result['msg']="支付成功";
            }else{
                Db::rollback();
                $result['code']=-9;
                $result['msg']="支付失败";
            }
            return json_encode($result);
        }else{ //消费券不足支付
            $wxmoney = $money;
            if($user['ywq']>0.01){
                $payywq = intval($user['ywq']*100)/100;
                $wxmoney = bcadd(bcmul($money-$payywq, 100, 2), '0', 0)/100;
                //生成店铺订单
                $data['user_id']=$user['user_id'];
                $data['order_sn']=get_order_sn();
                $data['shop_user_id']=$shop['user_id'];
                $data['money']=$payywq;
                $data['order_money']=$payywq;
                $data['money_type']=6;
                $data['remark']='商城订单';
                $data['status']=0;
                $data['order_type']=4;
                $data['create_time']=time();
                $data['pay_time']=time();
                $data['address_id']=$address_id;
                $data['total_order_id']=$torderadd->id;

                $shopadd=ShopPayOrder::create($data,true);
                if(!$shopadd){
                    $trans_ok = false;
                }
            }
            //生成微信支付订单
            //生成店铺订单
            $wxdata['user_id']=$user['user_id'];
            $wxdata['order_sn']=get_order_sn();
            $wxdata['shop_user_id']=$shop['user_id'];
            $wxdata['money']=$wxmoney;
            $wxdata['order_money']=$wxmoney;
            $wxdata['money_type']=1;
            $wxdata['remark']='商城订单';
            $wxdata['status']=0;
            $wxdata['order_type']=4;
            $wxdata['create_time']=time();
            $wxdata['total_order_id']=$torderadd->id;
            if($shop['money_type']==2){
                $wxdata['merchant_id'] = $shop['merchant_id'];
            }else{
                $wxdata['merchant_id'] = config("leshua.merchant_id");
            }
            $wxdata['shop_money_type']=$shop['money_type'];
            $shopadd2=ShopPayOrder::create($wxdata,true);
            if(!$shopadd2){
                $trans_ok=false;
            }
            if($trans_ok){
                Db::commit();
                $result['code']=1;
                $result['money']=$wxmoney;
                $result['order_sn']=$wxdata['order_sn'];
                $result['msg']="跳转到微支付";
            }else{
                Db::rollback();
                $result['code']=-9;
                $result['msg']="支付出错";
            }
            return json_encode($result);
        }
    }
}